# -*- coding: utf-8 -*-
#
# Sorto, the sorting game
# Copyright (C) 2012 Ralph Preston
# ralph.preston@gmail.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to:
#
# Free Software Foundation, Inc.
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301
# USA.
#
import os
import sys
import copy
import time
import math
import pprint
import datetime
import threading
import Queue

from PyQt4 import QtCore, QtGui
from sorto_start_server_dialog import Ui_ServerDialog

class StartServerDialog(QtGui.QDialog):

    SERVER_IP_CONFIG = '.sorto_xmlrpc_server_address'

    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.ui = Ui_ServerDialog()
        self.ui.setupUi(self)

        self._parent = parent

        self._ip = '127.0.0.1'
        self._port = '8000'

        data = []
        try:
            fd = open(self.SERVER_IP_CONFIG, 'r')
            data = fd.readlines()
            fd.close()
        except IOError:
            pass

        if len(data) >= 2:
            self._ip = data[0].strip()
            self._port = data[1].strip()
            pass
            
        self.ui.lineEdit_ip_address.setText(self._ip)
        self.ui.lineEdit_port.setText(self._port)
        return

    def accept(self):
        ip = self.ui.lineEdit_ip_address.displayText()
        port = self.ui.lineEdit_port.displayText()

        try:
            int(port)
        except ValueError:
            self._parent.startServerDialog_cancel_clicked("Failed to start server. Port number must be numeric")
            return

        if str(ip) != self._ip or str(port) != self._port:
            fd = open(self.SERVER_IP_CONFIG, 'w')
            fd.write('%s\n%s\n' % (str(ip), str(port)))
            fd.close()
            pass

        self._parent.startServerDialog_ok_clicked(str(ip), str(port))
        return

    def reject(self):
        self._parent.startServerDialog_cancel_clicked()
        return

    pass # End of class StartServerDialog
